package com.dnzx.base;


import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Component
public class TokenFilter implements Filter {
	
	//private TokenService tokenService;

	public Logger logger = LoggerFactory.getLogger(TokenFilter.class);
	
	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
 		HttpServletRequest request = (HttpServletRequest) servletRequest;
		String[] tokenValues;
		try {
			tokenValues = request.getParameterValues("token");
			if(tokenValues!=null && tokenValues.length>0){//检查 是否有token ,
				String token = tokenValues[0];
				String id = null;
				if(token.startsWith("hzweb-")){
					id = token.replace("hzweb-","");
				}else{
					//id = tokenService.getIdByToken(token);
				}
				if(StringUtils.isNotBlank(id)){//检查 是否token失效了?
					request.setAttribute("token",token);
					request.setAttribute("id",id);
					filterChain.doFilter(servletRequest, servletResponse);
					return;
				}
			}
		}catch (Exception e){
			logger.error("token过滤器发生了错误",e);
		}
		return;
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		ServletContext sc = filterConfig.getServletContext();
		WebApplicationContext wac = (WebApplicationContext) sc.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
	//	tokenService = (TokenService) wac.getBean("tokenService");
	}

	@Override
	public void destroy() {}

}
